package com.article.lock;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.exception.ZkException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * 会出现羊群效应
 */
public class ZookeeperDistributeLock extends ZookeeperAbstractLock {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperDistributeLock.class);
    private CountDownLatch cdl = null;

    @Override
    public void waitForLock() {
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("===================================");
                if (cdl != null) {
                    cdl.countDown();
                }
            }

            @Override
            public void handleDataChange(String dataPath, Object o) throws Exception {

            }
        };
        zkClient.subscribeDataChanges(path, listener);
        if (zkClient.exists(path)) {
            cdl = new CountDownLatch(1);
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        zkClient.unsubscribeDataChanges(path, listener);
    }

    @Override
    public boolean tryLock() {
        try {
            zkClient.createEphemeral(path);
            return true;
        } catch (ZkException e) {
            return false;
        }
    }
}
